package com.itheima.reggie.controller;


import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

//员工
@RestController
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    //这里注意，session可以直接注入  springboot已经将这个对象准备好了
    @Autowired
    private HttpSession httpSession;

    //接收前端请求，进行参数接收并调用业务层
    @PostMapping("/employee/login")
    public ResultInfo login(@RequestBody Map<String,String> map){
        //这里其实用map接可以，用对象接也可以，都一样
        String username = map.get("username");
        String password = map.get("password");
        //调用业务层返回结果对象
        ResultInfo resultInfo = employeeService.login(username, password);
        //不管登录成功与否，都要保存到session中，只不过没成功就保存的是null,也方便拦截器拦截
        httpSession.setAttribute("SESSION_EMPLOYEE",(Employee)resultInfo.getData());
        return resultInfo;
    }

    @PostMapping("/employee/logout")
    public ResultInfo logout(){
        //退出的操作，就是将session中的信息销毁
        //销毁session数据
        httpSession.invalidate();
        //返回数据  没什么可返回的
        return ResultInfo.success(null);
    }

    @GetMapping("/employee/find")
    public ResultInfo findEmployee(String name){
        List<Employee> employeeList = employeeService.findByName(name);

        return ResultInfo.success(employeeList);
    }

    //新增员工
    @PostMapping("/employee")
    public ResultInfo save(@RequestBody Employee employee){
        //这里还需要设置前端没有传过来的参数
        employee.setId(IdUtil.getSnowflake(1,1).nextId()); //雪花算法计算出来的id
        employee.setPassword(SecureUtil.md5("123"));
        employee.setStatus(Employee.STATUS_ENABLE);
//        employee.setCreateTime(new Date());
//        employee.setUpdateTime(new Date());
//        //这里的创建者和更新者可以使用session中的用户id
//        Employee employees = (Employee) httpSession.getAttribute("SESSION_EMPLOYEE");
//        employee.setCreateUser(employees.getId());
//        employee.setUpdateUser(employees.getId());
        //调用service保存用户
        ResultInfo resultInfo = employeeService.add(employee);
        return resultInfo;
    }

    //根据id查询员工
    @GetMapping("/employee/{id}")
    public ResultInfo findById(@PathVariable("id") Long id){
        Employee employee = employeeService.findById(id);
        return employee != null ? ResultInfo.success(employee) : ResultInfo.error("查询失败");
    }

    //修改员工信息
    @PutMapping("/employee")
    public ResultInfo update(@RequestBody Employee employee){
        Integer updateNum = employeeService.update(employee);
        return updateNum > 0 ? ResultInfo.success(employee) : ResultInfo.error("修改失败");
    }



}